package com.tianquan.miracle.postprocessor;/**
 * @author starsea
 * @date 2024-10-17 下午6:28
 */


import com.tianquan.miracle.util.MiracleUtils;
import jakarta.annotation.Resource;

import java.lang.reflect.Field;

/**
 * @BelongsProject: uploaddemo
 * @BelongsPackage: com.tianquan.miracle.postprocessor
 * @Author: tianquan
 * @CreateTime: 2024-10-17  18:28
 * @Description: 解析Resource
 * @Version: 1.0
 */
public class ResourceBeanPostProcessor implements InjectBeanPostProcessor {

    public void inject(Object bean) {
        Class<?> aClass = bean.getClass();
        for (Field field : aClass.getDeclaredFields()) {
            Resource resource = field.getAnnotation(Resource.class);
            if (resource == null) continue;
            field.setAccessible(true);
            try {
                // 优先根据名称注入
                Object value = MiracleUtils.getBean(field.getName());
                if (value == null) {
                    // 根据类型注入
                    Class<?> fieldClass = field.getClass();
                    value = MiracleUtils.getBean(fieldClass);
                    if (value == null) throw new RuntimeException("can not find bean is " + field.getName());
                }
                // 注入
                field.set(bean, value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
